{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# How to return citations\n",
        "\n",
        ":::info Prerequisites\n",
        "\n",
        "This guide assumes familiarity with the following:\n",
        "\n",
        "- [Retrieval-augmented generation](/docs/tutorials/rag/)\n",
        "- [Returning structured data from a model](/docs/how_to/structured_output/)\n",
        "\n",
        ":::\n",
        "\n",
        "How can we get a model to cite which parts of the source documents it referenced in its response?\n",
        "\n",
        "To explore some techniques for extracting citations, let's first create a simple RAG chain. To start we'll just retrieve from the web using the [`TavilySearchAPIRetriever`](https://api.js.langchain.com/classes/langchain_community_retrievers_tavily_search_api.TavilySearchAPIRetriever.html)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Setup\n",
        "### Dependencies\n",
        "\n",
        "We’ll use an OpenAI chat model and embeddings and a Memory vector store in this walkthrough, but everything shown here works with any [ChatModel](/docs/concepts/chat_models) or [LLM](/docs/concepts/text_llms), [Embeddings](/docs/concepts/embedding_models/), and [VectorStore](/docs/concepts/vectorstores/) or [Retriever](/docs/concepts/retrievers).\n",
        "\n",
        "We’ll use the following packages:\n",
        "\n",
        "```bash\n",
        "npm install --save langchain @langchain/community @langchain/openai\n",
        "```\n",
        "\n",
        "We need to set environment variables for Tavily Search & OpenAI:\n",
        "\n",
        "```bash\n",
        "export OPENAI_API_KEY=YOUR_KEY\n",
        "export TAVILY_API_KEY=YOUR_KEY\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### LangSmith\n",
        "\n",
        "Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com/).\n",
        "\n",
        "Note that LangSmith is not needed, but it is helpful. If you do want to use LangSmith, after you sign up at the link above, make sure to set your environment variables to start logging traces:\n",
        "\n",
        "\n",
        "```bash\n",
        "export LANGSMITH_TRACING=true\n",
        "export LANGSMITH_API_KEY=YOUR_KEY\n",
        "\n",
        "# Reduce tracing latency if you are not in a serverless environment\n",
        "# export LANGCHAIN_CALLBACKS_BACKGROUND=true\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Initial setup"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {},
      "outputs": [],
      "source": [
        "import { TavilySearchAPIRetriever } from \"@langchain/community/retrievers/tavily_search_api\";\n",
        "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
        "import { ChatOpenAI } from \"@langchain/openai\";\n",
        "\n",
        "const llm = new ChatOpenAI({\n",
        "  model: \"gpt-3.5-turbo\",\n",
        "  temperature: 0,\n",
        "});\n",
        "\n",
        "const retriever = new TavilySearchAPIRetriever({\n",
        "  k: 6,\n",
        "});\n",
        "\n",
        "const prompt = ChatPromptTemplate.fromMessages([\n",
        "  [\"system\", \"You're a helpful AI assistant. Given a user question and some web article snippets, answer the user question. If none of the articles answer the question, just say you don't know.\\n\\nHere are the web articles:{context}\"],\n",
        "  [\"human\", \"{question}\"],\n",
        "]);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now that we've got a model, retriever and prompt, let's chain them all together. We'll need to add some logic for formatting our retrieved `Document`s to a string that can be passed to our prompt. We'll make it so our chain returns both the answer and the retrieved Documents."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "{\n",
              "  answer: \u001b[32m\"Cheetahs are the fastest land animals on Earth. They can reach speeds as high as 75 mph or 120 km/h.\"\u001b[39m... 124 more characters,\n",
              "  docs: [\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"Contact Us − +\\n\"\u001b[39m +\n",
              "        \u001b[32m\"Address\\n\"\u001b[39m +\n",
              "        \u001b[32m\"Smithsonian's National Zoo & Conservation Biology Institute  3001 Connecticut\"\u001b[39m... 1343 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"Cheetah | Smithsonian's National Zoo and Conservation Biology Institute\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://nationalzoo.si.edu/animals/cheetah\"\u001b[39m,\n",
              "        score: \u001b[33m0.96283\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"Now, their only hope lies in the hands of human conservationists, working tirelessly to save the che\"\u001b[39m... 880 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"How Fast Are Cheetahs, and Other Fascinating Facts About the World's ...\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.discovermagazine.com/planet-earth/how-fast-are-cheetahs-and-other-fascinating-facts-abou\"\u001b[39m... 21 more characters,\n",
              "        score: \u001b[33m0.96052\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely r\"\u001b[39m... 1048 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"Cheetah | Description, Speed, Habitat, Diet, Cubs, & Facts\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.britannica.com/animal/cheetah-mammal\"\u001b[39m,\n",
              "        score: \u001b[33m0.93137\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"The science of cheetah speed\\n\"\u001b[39m +\n",
              "        \u001b[32m\"The cheetah (Acinonyx jubatus) is the fastest land animal on Earth, cap\"\u001b[39m... 738 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"How Fast Can a Cheetah Run? - ThoughtCo\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.thoughtco.com/how-fast-can-a-cheetah-run-4587031\"\u001b[39m,\n",
              "        score: \u001b[33m0.91385\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"One of two videos from National Geographic's award-winning multimedia coverage of cheetahs in the ma\"\u001b[39m... 60 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"The Science of a Cheetah's Speed | National Geographic\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.youtube.com/watch?v=icFMTB0Pi0g\"\u001b[39m,\n",
              "        score: \u001b[33m0.90358\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"If a lion comes along, the cheetah will abandon its catch -- it can't fight off a lion, and chances \"\u001b[39m... 911 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"What makes a cheetah run so fast? | HowStuffWorks\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://animals.howstuffworks.com/mammals/cheetah-speed.htm\"\u001b[39m,\n",
              "        score: \u001b[33m0.87824\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    }\n",
              "  ]\n",
              "}"
            ]
          },
          "execution_count": 2,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "import { Document } from \"@langchain/core/documents\";\n",
        "import { StringOutputParser } from \"@langchain/core/output_parsers\";\n",
        "import { RunnableMap, RunnablePassthrough } from \"@langchain/core/runnables\";\n",
        "\n",
        "/**\n",
        " * Format the documents into a readable string.\n",
        " */\n",
        "const formatDocs = (input: Record<string, any>): string => {\n",
        "  const { docs } = input;\n",
        "  return \"\\n\\n\" + docs.map((doc: Document) => `Article title: ${doc.metadata.title}\\nArticle Snippet: ${doc.pageContent}`).join(\"\\n\\n\");\n",
        "}\n",
        "// subchain for generating an answer once we've done retrieval\n",
        "const answerChain = prompt.pipe(llm).pipe(new StringOutputParser());\n",
        "const map = RunnableMap.from({\n",
        "  question: new RunnablePassthrough(),\n",
        "  docs: retriever,\n",
        "})\n",
        "// complete chain that calls the retriever -> formats docs to string -> runs answer subchain -> returns just the answer and retrieved docs.\n",
        "const chain = map.assign({ context: formatDocs }).assign({ answer: answerChain }).pick([\"answer\", \"docs\"])\n",
        "\n",
        "await chain.invoke(\"How fast are cheetahs?\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "See a LangSmith trace [here](https://smith.langchain.com/public/bb0ed37e-b2be-4ae9-8b0d-ce2aff0b4b5e/r) that shows off the internals."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Tool calling\n",
        "\n",
        "### Cite documents\n",
        "Let's try using [tool calling](/docs/how_to/tool_calling) to make the model specify which of the provided documents it's actually referencing when answering. LangChain has some utils for converting objects or [Zod](https://zod.dev) objects to the JSONSchema format expected by providers like OpenAI. We'll use the [`.withStructuredOutput()`](/docs/how_to/structured_output/) method to get the model to output data matching our desired schema:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "{\n",
              "  answer: \u001b[32m`Brian is 6'2\" - 3 inches = 5'11\" tall.`\u001b[39m,\n",
              "  citations: [ \u001b[33m1\u001b[39m, \u001b[33m3\u001b[39m ]\n",
              "}"
            ]
          },
          "execution_count": 3,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "import { z } from \"zod\";\n",
        "\n",
        "const llmWithTool1 = llm.withStructuredOutput(\n",
        "  z.object({\n",
        "    answer: z.string().describe(\"The answer to the user question, which is based only on the given sources.\"),\n",
        "    citations: z.array(z.number()).describe(\"The integer IDs of the SPECIFIC sources which justify the answer.\")\n",
        "  }).describe(\"A cited source from the given text\"),\n",
        "  {\n",
        "    name: \"cited_answers\"\n",
        "  }\n",
        ");\n",
        "\n",
        "const exampleQ = `What is Brian's height?\n",
        "\n",
        "Source: 1\n",
        "Information: Suzy is 6'2\"\n",
        "\n",
        "Source: 2\n",
        "Information: Jeremiah is blonde\n",
        "\n",
        "Source: 3\n",
        "Information: Brian is 3 inches shorter than Suzy`;\n",
        "\n",
        "await llmWithTool1.invoke(exampleQ);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "See a LangSmith trace [here](https://smith.langchain.com/public/28736c75-122e-4deb-9916-55c73eea3167/r) that shows off the internals"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now we're ready to put together our chain"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "{\n",
              "  cited_answer: {\n",
              "    answer: \u001b[32m\"Cheetahs can reach speeds as high as 75 mph or 120 km/h.\"\u001b[39m,\n",
              "    citations: [ \u001b[33m1\u001b[39m, \u001b[33m2\u001b[39m, \u001b[33m5\u001b[39m ]\n",
              "  },\n",
              "  docs: [\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"One of two videos from National Geographic's award-winning multimedia coverage of cheetahs in the ma\"\u001b[39m... 60 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"The Science of a Cheetah's Speed | National Geographic\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.youtube.com/watch?v=icFMTB0Pi0g\"\u001b[39m,\n",
              "        score: \u001b[33m0.97858\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely r\"\u001b[39m... 1048 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"Cheetah | Description, Speed, Habitat, Diet, Cubs, & Facts\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.britannica.com/animal/cheetah-mammal\"\u001b[39m,\n",
              "        score: \u001b[33m0.97213\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"The science of cheetah speed\\n\"\u001b[39m +\n",
              "        \u001b[32m\"The cheetah (Acinonyx jubatus) is the fastest land animal on Earth, cap\"\u001b[39m... 738 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"How Fast Can a Cheetah Run? - ThoughtCo\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.thoughtco.com/how-fast-can-a-cheetah-run-4587031\"\u001b[39m,\n",
              "        score: \u001b[33m0.95759\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"Contact Us − +\\n\"\u001b[39m +\n",
              "        \u001b[32m\"Address\\n\"\u001b[39m +\n",
              "        \u001b[32m\"Smithsonian's National Zoo & Conservation Biology Institute  3001 Connecticut\"\u001b[39m... 1343 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"Cheetah | Smithsonian's National Zoo and Conservation Biology Institute\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://nationalzoo.si.edu/animals/cheetah\"\u001b[39m,\n",
              "        score: \u001b[33m0.92422\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"Now, their only hope lies in the hands of human conservationists, working tirelessly to save the che\"\u001b[39m... 880 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"How Fast Are Cheetahs, and Other Fascinating Facts About the World's ...\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.discovermagazine.com/planet-earth/how-fast-are-cheetahs-and-other-fascinating-facts-abou\"\u001b[39m... 21 more characters,\n",
              "        score: \u001b[33m0.91867\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"The speeds attained by the cheetah may be only slightly greater than those achieved by the pronghorn\"\u001b[39m... 2527 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"Cheetah - Wikipedia\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://en.wikipedia.org/wiki/Cheetah\"\u001b[39m,\n",
              "        score: \u001b[33m0.81617\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    }\n",
              "  ]\n",
              "}"
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "import { Document } from \"@langchain/core/documents\";\n",
        "\n",
        "const formatDocsWithId = (docs: Array<Document>): string => {\n",
        "  return \"\\n\\n\" + docs.map((doc: Document, idx: number) => `Source ID: ${idx}\\nArticle title: ${doc.metadata.title}\\nArticle Snippet: ${doc.pageContent}`).join(\"\\n\\n\");\n",
        "}\n",
        "// subchain for generating an answer once we've done retrieval\n",
        "const answerChain1 = prompt.pipe(llmWithTool1);\n",
        "const map1 = RunnableMap.from({\n",
        "  question: new RunnablePassthrough(),\n",
        "  docs: retriever,\n",
        "})\n",
        "// complete chain that calls the retriever -> formats docs to string -> runs answer subchain -> returns just the answer and retrieved docs.\n",
        "const chain1 = map1\n",
        "  .assign({ context: (input: { docs: Array<Document> }) => formatDocsWithId(input.docs) })\n",
        "  .assign({ cited_answer: answerChain1 })\n",
        "  .pick([\"cited_answer\", \"docs\"])\n",
        "  \n",
        "await chain1.invoke(\"How fast are cheetahs?\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "See a LangSmith trace [here](https://smith.langchain.com/public/86814255-b9b0-4c4f-9463-e795c9961451/r) that shows off the internals."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Cite snippets\n",
        "\n",
        "What if we want to cite actual text spans? We can try to get our model to return these, too.\n",
        "\n",
        "**Note**: Note that if we break up our documents so that we have many documents with only a sentence or two instead of a few long documents, citing documents becomes roughly equivalent to citing snippets, and may be easier for the model because the model just needs to return an identifier for each snippet instead of the actual text. We recommend trying both approaches and evaluating."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "{\n",
              "  quoted_answer: {\n",
              "    answer: \u001b[32m\"Cheetahs can reach speeds of up to 120kph or 75mph, making them the world’s fastest land animals.\"\u001b[39m,\n",
              "    citations: [\n",
              "      {\n",
              "        sourceId: \u001b[33m5\u001b[39m,\n",
              "        quote: \u001b[32m\"Cheetahs can reach speeds of up to 120kph or 75mph, making them the world’s fastest land animals.\"\u001b[39m\n",
              "      },\n",
              "      {\n",
              "        sourceId: \u001b[33m1\u001b[39m,\n",
              "        quote: \u001b[32m\"The cheetah (Acinonyx jubatus) is the fastest land animal on Earth, capable of reaching speeds as hi\"\u001b[39m... 25 more characters\n",
              "      },\n",
              "      {\n",
              "        sourceId: \u001b[33m3\u001b[39m,\n",
              "        quote: \u001b[32m\"The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely r\"\u001b[39m... 72 more characters\n",
              "      }\n",
              "    ]\n",
              "  },\n",
              "  docs: [\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"Contact Us − +\\n\"\u001b[39m +\n",
              "        \u001b[32m\"Address\\n\"\u001b[39m +\n",
              "        \u001b[32m\"Smithsonian's National Zoo & Conservation Biology Institute  3001 Connecticut\"\u001b[39m... 1343 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"Cheetah | Smithsonian's National Zoo and Conservation Biology Institute\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://nationalzoo.si.edu/animals/cheetah\"\u001b[39m,\n",
              "        score: \u001b[33m0.95973\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"The science of cheetah speed\\n\"\u001b[39m +\n",
              "        \u001b[32m\"The cheetah (Acinonyx jubatus) is the fastest land animal on Earth, cap\"\u001b[39m... 738 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"How Fast Can a Cheetah Run? - ThoughtCo\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.thoughtco.com/how-fast-can-a-cheetah-run-4587031\"\u001b[39m,\n",
              "        score: \u001b[33m0.92749\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"Now, their only hope lies in the hands of human conservationists, working tirelessly to save the che\"\u001b[39m... 880 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"How Fast Are Cheetahs, and Other Fascinating Facts About the World's ...\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.discovermagazine.com/planet-earth/how-fast-are-cheetahs-and-other-fascinating-facts-abou\"\u001b[39m... 21 more characters,\n",
              "        score: \u001b[33m0.92417\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely r\"\u001b[39m... 1048 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"Cheetah | Description, Speed, Habitat, Diet, Cubs, & Facts\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.britannica.com/animal/cheetah-mammal\"\u001b[39m,\n",
              "        score: \u001b[33m0.92341\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"One of two videos from National Geographic's award-winning multimedia coverage of cheetahs in the ma\"\u001b[39m... 60 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"The Science of a Cheetah's Speed | National Geographic\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://www.youtube.com/watch?v=icFMTB0Pi0g\"\u001b[39m,\n",
              "        score: \u001b[33m0.90025\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    },\n",
              "    Document {\n",
              "      pageContent: \u001b[32m\"In fact, they are more closely related to kangaroos…\\n\"\u001b[39m +\n",
              "        \u001b[32m\"Read more\\n\"\u001b[39m +\n",
              "        \u001b[32m\"Animals on the Galapagos Islands: A G\"\u001b[39m... 987 more characters,\n",
              "      metadata: {\n",
              "        title: \u001b[32m\"How fast can cheetahs run, and what enables their incredible speed?\"\u001b[39m,\n",
              "        source: \u001b[32m\"https://wildlifefaq.com/cheetah-speed/\"\u001b[39m,\n",
              "        score: \u001b[33m0.87121\u001b[39m,\n",
              "        images: \u001b[1mnull\u001b[22m\n",
              "      }\n",
              "    }\n",
              "  ]\n",
              "}"
            ]
          },
          "execution_count": 5,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "import { Document } from \"@langchain/core/documents\";\n",
        "\n",
        "const citationSchema = z.object({\n",
        "  sourceId: z.number().describe(\"The integer ID of a SPECIFIC source which justifies the answer.\"),\n",
        "  quote: z.string().describe(\"The VERBATIM quote from the specified source that justifies the answer.\")\n",
        "});\n",
        "\n",
        "const llmWithTool2 = llm.withStructuredOutput(\n",
        "  z.object({\n",
        "    answer: z.string().describe(\"The answer to the user question, which is based only on the given sources.\"),\n",
        "    citations: z.array(citationSchema).describe(\"Citations from the given sources that justify the answer.\")\n",
        "  }), {\n",
        "    name: \"quoted_answer\",\n",
        "  })\n",
        "\n",
        "const answerChain2 = prompt.pipe(llmWithTool2);\n",
        "const map2 = RunnableMap.from({\n",
        "  question: new RunnablePassthrough(),\n",
        "  docs: retriever,\n",
        "})\n",
        "// complete chain that calls the retriever -> formats docs to string -> runs answer subchain -> returns just the answer and retrieved docs.\n",
        "const chain2 = map2\n",
        "  .assign({ context: (input: { docs: Array<Document> }) => formatDocsWithId(input.docs) })\n",
        "  .assign({ quoted_answer: answerChain2 })\n",
        "  .pick([\"quoted_answer\", \"docs\"]);\n",
        "  \n",
        "await chain2.invoke(\"How fast are cheetahs?\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "You can check out a LangSmith trace [here](https://smith.langchain.com/public/f0588adc-1914-45e8-a2ed-4fa028cea0e1/r) that shows off the internals."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Direct prompting\n",
        "\n",
        "Not all models support tool-calling. We can achieve similar results with direct prompting. Let's see what this looks like using an older Anthropic chat model that is particularly proficient in working with XML:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Setup\n",
        "\n",
        "Install the LangChain Anthropic integration package:\n",
        "\n",
        "```bash\n",
        "npm install @langchain/anthropic\n",
        "```\n",
        "\n",
        "Add your Anthropic API key to your environment:\n",
        "\n",
        "```bash\n",
        "export ANTHROPIC_API_KEY=YOUR_KEY\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{\n",
            "  \"cited_answer\": [\n",
            "    {\n",
            "      \"answer\": \"Cheetahs can reach top speeds of around 75 mph, but can only maintain bursts of speed for short distances before tiring.\"\n",
            "    },\n",
            "    {\n",
            "      \"citations\": [\n",
            "        {\n",
            "          \"citation\": [\n",
            "            {\n",
            "              \"source_id\": \"1\"\n",
            "            },\n",
            "            {\n",
            "              \"quote\": \"Scientists calculate a cheetah's top speed is 75 mph, but the fastest recorded speed is somewhat slower.\"\n",
            "            }\n",
            "          ]\n",
            "        },\n",
            "        {\n",
            "          \"citation\": [\n",
            "            {\n",
            "              \"source_id\": \"3\"\n",
            "            },\n",
            "            {\n",
            "              \"quote\": \"The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely reach velocities of 80–100 km (50–62 miles) per hour while pursuing prey.\"\n",
            "            }\n",
            "          ]\n",
            "        }\n",
            "      ]\n",
            "    }\n",
            "  ],\n",
            "  \"docs\": [\n",
            "    {\n",
            "      \"pageContent\": \"One of two videos from National Geographic's award-winning multimedia coverage of cheetahs in the magazine's November 2012 iPad edition. See the other: http:...\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"The Science of a Cheetah's Speed | National Geographic\",\n",
            "        \"source\": \"https://www.youtube.com/watch?v=icFMTB0Pi0g\",\n",
            "        \"score\": 0.96603,\n",
            "        \"images\": null\n",
            "      }\n",
            "    },\n",
            "    {\n",
            "      \"pageContent\": \"The science of cheetah speed\\nThe cheetah (Acinonyx jubatus) is the fastest land animal on Earth, capable of reaching speeds as high as 75 mph or 120 km/h. Cheetahs are predators that sneak up on their prey and sprint a short distance to chase and attack.\\n Key Takeaways: How Fast Can a Cheetah Run?\\nFastest Cheetah on Earth\\nScientists calculate a cheetah's top speed is 75 mph, but the fastest recorded speed is somewhat slower. The top 10 fastest animals are:\\nThe pronghorn, an American animal resembling an antelope, is the fastest land animal in the Western Hemisphere. While a cheetah's top speed ranges from 65 to 75 mph (104 to 120 km/h), its average speed is only 40 mph (64 km/hr), punctuated by short bursts at its top speed. Basically, if a predator threatens to take a cheetah's kill or attack its young, a cheetah has to run.\\n\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"How Fast Can a Cheetah Run? - ThoughtCo\",\n",
            "        \"source\": \"https://www.thoughtco.com/how-fast-can-a-cheetah-run-4587031\",\n",
            "        \"score\": 0.96212,\n",
            "        \"images\": null\n",
            "      }\n",
            "    },\n",
            "    {\n",
            "      \"pageContent\": \"Now, their only hope lies in the hands of human conservationists, working tirelessly to save the cheetahs, the leopards and all the other wildlife of the scattered savannas and other habitats of Africa and Asia.\\n Their tough paw pads and grippy claws are made to grab at the ground, and their large nasal passages and lungs facilitate the flow of oxygen and allow their rapid intake of air as they reach their top speeds.\\n And though the two cats share a similar coloration, a cheetah's spots are circular while a leopard's spots are rose-shaped \\\"rosettes,\\\" with the centers of their spots showing off the tan color of their coats.\\n Also classified as \\\"vulnerable\\\" are two of the cheetah's foremost foes, the lion and the leopard, the latter of which is commonly confused for the cheetah thanks to its own flecked fur.\\n The cats are also consumers of the smallest of the bigger, bulkier antelopes, such as sables and kudus, and are known to gnaw on the occasional rabbit or bird.\\n\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"How Fast Are Cheetahs, and Other Fascinating Facts About the World's ...\",\n",
            "        \"source\": \"https://www.discovermagazine.com/planet-earth/how-fast-are-cheetahs-and-other-fascinating-facts-about-the-worlds-quickest\",\n",
            "        \"score\": 0.95688,\n",
            "        \"images\": null\n",
            "      }\n",
            "    },\n",
            "    {\n",
            "      \"pageContent\": \"The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely reach velocities of 80–100 km (50–62 miles) per hour while pursuing prey.\\ncheetah,\\n(Acinonyx jubatus),\\none of the world’s most-recognizable cats, known especially for its speed. Their fur is dark and includes a thick yellowish gray mane along the back, a trait that presumably offers better camouflage and increased protection from high temperatures during the day and low temperatures at night during the first few months of life. Cheetahs eat a variety of small animals, including game birds, rabbits, small antelopes (including the springbok, impala, and gazelle), young warthogs, and larger antelopes (such as the kudu, hartebeest, oryx, and roan).\\n A cheetah eats a variety of small animals, including game birds, rabbits, small antelopes (including the springbok, impala, and gazelle), young warthogs, and larger antelopes (such as the kudu, hartebeest, oryx, and roan). Their faces are distinguished by prominent black lines that curve from the inner corner of each eye to the outer corners of the mouth, like a well-worn trail of inky tears.\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"Cheetah | Description, Speed, Habitat, Diet, Cubs, & Facts\",\n",
            "        \"source\": \"https://www.britannica.com/animal/cheetah-mammal\",\n",
            "        \"score\": 0.95589,\n",
            "        \"images\": null\n",
            "      }\n",
            "    },\n",
            "    {\n",
            "      \"pageContent\": \"Contact Us − +\\nAddress\\nSmithsonian's National Zoo & Conservation Biology Institute  3001 Connecticut Ave., NW  Washington, DC 20008\\nAbout the Zoo\\n−\\n+\\nCareers\\n−\\n+\\nNews & Media\\n−\\n+\\nFooter Donate\\n−\\n+\\nShop\\n−\\n+\\nFollow us on social media\\nSign Up for Emails\\nFooter - SI logo, privacy, terms Conservation Efforts\\nHistorically, cheetahs ranged widely throughout Africa and Asia, from the Cape of Good Hope to the Mediterranean, throughout the Arabian Peninsula and the Middle East, from Israel, India and Pakistan north to the northern shores of the Caspian and Aral Seas, and west through Uzbekistan, Turkmenistan, Afghanistan, and Pakistan into central India. Header Links\\nToday's hours: 8 a.m. to 4 p.m. (last entry 3 p.m.)\\nMega menu\\nAnimals Global Nav Links\\nElephant Cam\\nSee the Smithsonian's National Zoo's Asian elephants — Spike, Bozie, Kamala, Swarna and Maharani — both inside the Elephant Community Center and outside in their yards.\\n Conservation Global Nav Links\\nAbout the Smithsonian Conservation Biology Institute\\nCheetah\\nAcinonyx jubatus\\nBuilt for speed, the cheetah can accelerate from zero to 45 in just 2.5 seconds and reach top speeds of 60 to 70 mph, making it the fastest land mammal! Fun Facts\\nConservation Status\\nCheetah News\\nTaxonomic Information\\nAnimal News\\nNZCBI staff in Front Royal, Virginia, are mourning the loss of Walnut, a white-naped crane who became an internet sensation for choosing one of her keepers as her mate.\\n\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"Cheetah | Smithsonian's National Zoo and Conservation Biology Institute\",\n",
            "        \"source\": \"https://nationalzoo.si.edu/animals/cheetah\",\n",
            "        \"score\": 0.94744,\n",
            "        \"images\": null\n",
            "      }\n",
            "    },\n",
            "    {\n",
            "      \"pageContent\": \"The speeds attained by the cheetah may be only slightly greater than those achieved by the pronghorn at 88.5 km/h (55.0 mph)[96] and the springbok at 88 km/h (55 mph),[97] but the cheetah additionally has an exceptional acceleration.[98]\\nOne stride of a galloping cheetah measures 4 to 7 m (13 to 23 ft); the stride length and the number of jumps increases with speed.[60] During more than half the duration of the sprint, the cheetah has all four limbs in the air, increasing the stride length.[99] Running cheetahs can retain up to 90% of the heat generated during the chase. In December 2016 the results of an extensive survey detailing the distribution and demography of cheetahs throughout the range were published; the researchers recommended listing the cheetah as Endangered on the IUCN Red List.[25]\\nThe cheetah was reintroduced in Malawi in 2017.[160]\\nIn Asia\\nIn 2001, the Iranian government collaborated with the CCF, the IUCN, Panthera Corporation, UNDP and the Wildlife Conservation Society on the Conservation of Asiatic Cheetah Project (CACP) to protect the natural habitat of the Asiatic cheetah and its prey.[161][162] Individuals on the periphery of the prey herd are common targets; vigilant prey which would react quickly on seeing the cheetah are not preferred.[47][60][122]\\nCheetahs are one of the most iconic pursuit predators, hunting primarily throughout the day, sometimes with peaks at dawn and dusk; they tend to avoid larger predators like the primarily nocturnal lion.[66] Cheetahs in the Sahara and Maasai Mara in Kenya hunt after sunset to escape the high temperatures of the day.[123] Cheetahs use their vision to hunt instead of their sense of smell; they keep a lookout for prey from resting sites or low branches. This significantly sharpens the vision and enables the cheetah to swiftly locate prey against the horizon.[61][86] The cheetah is unable to roar due to the presence of a sharp-edged vocal fold within the larynx.[2][87]\\nSpeed and acceleration\\nThe cheetah is the world's fastest land animal.[88][89][90][91][92] Estimates of the maximum speed attained range from 80 to 128 km/h (50 to 80 mph).[60][63] A commonly quoted value is 112 km/h (70 mph), recorded in 1957, but this measurement is disputed.[93] The mouth can not be opened as widely as in other cats given the shorter length of muscles between the jaw and the skull.[60][65] A study suggested that the limited retraction of the cheetah's claws may result from the earlier truncation of the development of the middle phalanx bone in cheetahs.[77]\\nThe cheetah has a total of 30 teeth; the dental formula is 3.1.3.13.1.2.1.\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"Cheetah - Wikipedia\",\n",
            "        \"source\": \"https://en.wikipedia.org/wiki/Cheetah\",\n",
            "        \"score\": 0.81312,\n",
            "        \"images\": null\n",
            "      }\n",
            "    }\n",
            "  ]\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "import { ChatAnthropic } from \"@langchain/anthropic\";\n",
        "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
        "import { XMLOutputParser } from \"@langchain/core/output_parsers\";\n",
        "import { Document } from \"@langchain/core/documents\";\n",
        "import { RunnableLambda, RunnablePassthrough, RunnableMap } from \"@langchain/core/runnables\";\n",
        "\n",
        "const anthropic = new ChatAnthropic({\n",
        "  model: \"claude-instant-1.2\",\n",
        "  temperature: 0,\n",
        "});\n",
        "const system = `You're a helpful AI assistant. Given a user question and some web article snippets,\n",
        "answer the user question and provide citations. If none of the articles answer the question, just say you don't know.\n",
        "\n",
        "Remember, you must return both an answer and citations. A citation consists of a VERBATIM quote that\n",
        "justifies the answer and the ID of the quote article. Return a citation for every quote across all articles\n",
        "that justify the answer. Use the following format for your final output:\n",
        "\n",
        "<cited_answer>\n",
        "    <answer></answer>\n",
        "    <citations>\n",
        "        <citation><source_id></source_id><quote></quote></citation>\n",
        "        <citation><source_id></source_id><quote></quote></citation>\n",
        "        ...\n",
        "    </citations>\n",
        "</cited_answer>\n",
        "\n",
        "Here are the web articles:{context}`;\n",
        "\n",
        "const anthropicPrompt = ChatPromptTemplate.fromMessages([\n",
        "  [\"system\", system],\n",
        "  [\"human\", \"{question}\"]\n",
        "]);\n",
        "\n",
        "const formatDocsToXML = (docs: Array<Document>): string => {\n",
        "  const formatted: Array<string> = [];\n",
        "  docs.forEach((doc, idx) => {\n",
        "    const docStr = `<source id=\"${idx}\">\n",
        "  <title>${doc.metadata.title}</title>\n",
        "  <article_snippet>${doc.pageContent}</article_snippet>\n",
        "</source>`\n",
        "    formatted.push(docStr);\n",
        "  });\n",
        "  return `\\n\\n<sources>${formatted.join(\"\\n\")}</sources>`;\n",
        "}\n",
        "\n",
        "const format3 = new RunnableLambda({\n",
        "  func: (input: { docs: Array<Document> }) => formatDocsToXML(input.docs)\n",
        "})\n",
        "const answerChain = anthropicPrompt\n",
        "  .pipe(anthropic)\n",
        "  .pipe(new XMLOutputParser())\n",
        "  .pipe(\n",
        "    new RunnableLambda({ func: (input: { cited_answer: any }) => input.cited_answer })\n",
        "  );\n",
        "const map3 = RunnableMap.from({\n",
        "  question: new RunnablePassthrough(),\n",
        "  docs: retriever,\n",
        "});\n",
        "const chain3 = map3.assign({ context: format3 }).assign({ cited_answer: answerChain }).pick([\"cited_answer\", \"docs\"])\n",
        "\n",
        "const res = await chain3.invoke(\"How fast are cheetahs?\");\n",
        "\n",
        "console.log(JSON.stringify(res, null, 2));"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Check out this LangSmith trace [here](https://smith.langchain.com/public/e2e938e8-f847-4ea8-bc84-43d4eaf8e524/r) for more on the internals."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Retrieval post-processing\n",
        "\n",
        "Another approach is to post-process our retrieved documents to compress the content, so that the source content is already minimal enough that we don't need the model to cite specific sources or spans. For example, we could break up each document into a sentence or two, embed those and keep only the most relevant ones. LangChain has some built-in components for this. Here we'll use a [`RecursiveCharacterTextSplitter`](/docs/how_to/recursive_text_splitter), which creates chunks of a specified size by splitting on separator substrings, and an [`EmbeddingsFilter`](/docs/how_to/contextual_compression), which keeps only the texts with the most relevant embeddings."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely reach velocities of 80–100 km (50–62 miles) per hour while pursuing prey.\n",
            "cheetah,\n",
            "(Acinonyx jubatus), \n",
            "\n",
            "\n",
            "The science of cheetah speed\n",
            "The cheetah (Acinonyx jubatus) is the fastest land animal on Earth, capable of reaching speeds as high as 75 mph or 120 km/h. Cheetahs are predators that sneak up on their prey and sprint a short distance to chase and attack.\n",
            " Key Takeaways: How Fast Can a Cheetah Run?\n",
            "Fastest Cheetah on Earth \n",
            "\n",
            "\n",
            "Built for speed, the cheetah can accelerate from zero to 45 in just 2.5 seconds and reach top speeds of 60 to 70 mph, making it the fastest land mammal! Fun Facts\n",
            "Conservation Status\n",
            "Cheetah News\n",
            "Taxonomic Information\n",
            "Animal News\n",
            "NZCBI staff in Front Royal, Virginia, are mourning the loss of Walnut, a white-naped crane who became an internet sensation for choosing one of her keepers as her mate. \n",
            "\n",
            "\n",
            "The speeds attained by the cheetah may be only slightly greater than those achieved by the pronghorn at 88.5 km/h (55.0 mph)[96] and the springbok at 88 km/h (55 mph),[97] but the cheetah additionally has an exceptional acceleration.[98] \n",
            "\n",
            "\n",
            "The cheetah is the world's fastest land animal.[88][89][90][91][92] Estimates of the maximum speed attained range from 80 to 128 km/h (50 to 80 mph).[60][63] A commonly quoted value is 112 km/h (70 mph), recorded in 1957, but this measurement is disputed.[93] The mouth can not be opened as widely as in other cats given the shorter length of muscles between the jaw and the skull \n",
            "\n",
            "\n",
            "Scientists calculate a cheetah's top speed is 75 mph, but the fastest recorded speed is somewhat slower. The top 10 fastest animals are: \n",
            "\n",
            "\n",
            "One stride of a galloping cheetah measures 4 to 7 m (13 to 23 ft); the stride length and the number of jumps increases with speed.[60] During more than half the duration of the sprint, the cheetah has all four limbs in the air, increasing the stride length.[99] Running cheetahs can retain up to 90% of the heat generated during the chase \n",
            "\n",
            "\n",
            "The pronghorn, an American animal resembling an antelope, is the fastest land animal in the Western Hemisphere. While a cheetah's top speed ranges from 65 to 75 mph (104 to 120 km/h), its average speed is only 40 mph (64 km/hr), punctuated by short bursts at its top speed. Basically, if a predator threatens to take a cheetah's kill or attack its young, a cheetah has to run. \n",
            "\n",
            "\n",
            "A cheetah eats a variety of small animals, including game birds, rabbits, small antelopes (including the springbok, impala, and gazelle), young warthogs, and larger antelopes (such as the kudu, hartebeest, oryx, and roan). Their faces are distinguished by prominent black lines that curve from the inner corner of each eye to the outer corners of the mouth, like a well-worn trail of inky tears. \n",
            "\n",
            "\n",
            "Cheetahs are one of the most iconic pursuit predators, hunting primarily throughout the day, sometimes with peaks at dawn and dusk; they tend to avoid larger predators like the primarily nocturnal lion.[66] Cheetahs in the Sahara and Maasai Mara in Kenya hunt after sunset to escape the high temperatures of the day \n",
            "\n",
            "\n"
          ]
        }
      ],
      "source": [
        "import { RecursiveCharacterTextSplitter } from \"langchain/text_splitter\";\n",
        "import { EmbeddingsFilter } from \"langchain/retrievers/document_compressors/embeddings_filter\";\n",
        "import { OpenAIEmbeddings } from \"@langchain/openai\";\n",
        "import { DocumentInterface } from \"@langchain/core/documents\";\n",
        "import { RunnableMap, RunnablePassthrough } from \"@langchain/core/runnables\";\n",
        "\n",
        "const splitter = new RecursiveCharacterTextSplitter({\n",
        "  chunkSize: 400,\n",
        "  chunkOverlap: 0,\n",
        "  separators: [\"\\n\\n\", \"\\n\", \".\", \" \"],\n",
        "  keepSeparator: false,\n",
        "});\n",
        "\n",
        "const compressor = new EmbeddingsFilter({\n",
        "  embeddings: new OpenAIEmbeddings(),\n",
        "  k: 10,\n",
        "});\n",
        "\n",
        "const splitAndFilter = async (input): Promise<Array<DocumentInterface>> => {\n",
        "  const { docs, question } = input;\n",
        "  const splitDocs = await splitter.splitDocuments(docs);\n",
        "  const statefulDocs = await compressor.compressDocuments(splitDocs, question);\n",
        "  return statefulDocs;\n",
        "};\n",
        "\n",
        "const retrieveMap = RunnableMap.from({\n",
        "  question: new RunnablePassthrough(),\n",
        "  docs: retriever,\n",
        "});\n",
        "\n",
        "const retriever = retrieveMap.pipe(splitAndFilter);\n",
        "const docs = await retriever.invoke(\"How fast are cheetahs?\");\n",
        "for (const doc of docs) {\n",
        "  console.log(doc.pageContent, \"\\n\\n\");\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "See the LangSmith trace [here](https://smith.langchain.com/public/ae6b1f52-c1fe-49ec-843c-92edf2104652/r) to see the internals."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{\n",
            "  \"answer\": [\n",
            "    {\n",
            "      \"answer\": \"\\nCheetahs are the fastest land animals. They can reach top speeds between 75-81 mph (120-130 km/h). \\n\"\n",
            "    },\n",
            "    {\n",
            "      \"citations\": [\n",
            "        {\n",
            "          \"citation\": [\n",
            "            {\n",
            "              \"source_id\": \"Article title: How Fast Can a Cheetah Run? - ThoughtCo\"\n",
            "            },\n",
            "            {\n",
            "              \"quote\": \"The science of cheetah speed\\nThe cheetah (Acinonyx jubatus) is the fastest land animal on Earth, capable of reaching speeds as high as 75 mph or 120 km/h.\"\n",
            "            }\n",
            "          ]\n",
            "        },\n",
            "        {\n",
            "          \"citation\": [\n",
            "            {\n",
            "              \"source_id\": \"Article title: Cheetah - Wikipedia\"\n",
            "            },\n",
            "            {\n",
            "              \"quote\": \"Scientists calculate a cheetah's top speed is 75 mph, but the fastest recorded speed is somewhat slower.\"\n",
            "            }\n",
            "          ]\n",
            "        }\n",
            "      ]\n",
            "    }\n",
            "  ],\n",
            "  \"docs\": [\n",
            "    {\n",
            "      \"pageContent\": \"The science of cheetah speed\\nThe cheetah (Acinonyx jubatus) is the fastest land animal on Earth, capable of reaching speeds as high as 75 mph or 120 km/h. Cheetahs are predators that sneak up on their prey and sprint a short distance to chase and attack.\\n Key Takeaways: How Fast Can a Cheetah Run?\\nFastest Cheetah on Earth\\nScientists calculate a cheetah's top speed is 75 mph, but the fastest recorded speed is somewhat slower. The top 10 fastest animals are:\\nThe pronghorn, an American animal resembling an antelope, is the fastest land animal in the Western Hemisphere. While a cheetah's top speed ranges from 65 to 75 mph (104 to 120 km/h), its average speed is only 40 mph (64 km/hr), punctuated by short bursts at its top speed. Basically, if a predator threatens to take a cheetah's kill or attack its young, a cheetah has to run.\\n\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"How Fast Can a Cheetah Run? - ThoughtCo\",\n",
            "        \"source\": \"https://www.thoughtco.com/how-fast-can-a-cheetah-run-4587031\",\n",
            "        \"score\": 0.96949,\n",
            "        \"images\": null\n",
            "      }\n",
            "    },\n",
            "    {\n",
            "      \"pageContent\": \"The speeds attained by the cheetah may be only slightly greater than those achieved by the pronghorn at 88.5 km/h (55.0 mph)[96] and the springbok at 88 km/h (55 mph),[97] but the cheetah additionally has an exceptional acceleration.[98]\\nOne stride of a galloping cheetah measures 4 to 7 m (13 to 23 ft); the stride length and the number of jumps increases with speed.[60] During more than half the duration of the sprint, the cheetah has all four limbs in the air, increasing the stride length.[99] Running cheetahs can retain up to 90% of the heat generated during the chase. In December 2016 the results of an extensive survey detailing the distribution and demography of cheetahs throughout the range were published; the researchers recommended listing the cheetah as Endangered on the IUCN Red List.[25]\\nThe cheetah was reintroduced in Malawi in 2017.[160]\\nIn Asia\\nIn 2001, the Iranian government collaborated with the CCF, the IUCN, Panthera Corporation, UNDP and the Wildlife Conservation Society on the Conservation of Asiatic Cheetah Project (CACP) to protect the natural habitat of the Asiatic cheetah and its prey.[161][162] Individuals on the periphery of the prey herd are common targets; vigilant prey which would react quickly on seeing the cheetah are not preferred.[47][60][122]\\nCheetahs are one of the most iconic pursuit predators, hunting primarily throughout the day, sometimes with peaks at dawn and dusk; they tend to avoid larger predators like the primarily nocturnal lion.[66] Cheetahs in the Sahara and Maasai Mara in Kenya hunt after sunset to escape the high temperatures of the day.[123] Cheetahs use their vision to hunt instead of their sense of smell; they keep a lookout for prey from resting sites or low branches. This significantly sharpens the vision and enables the cheetah to swiftly locate prey against the horizon.[61][86] The cheetah is unable to roar due to the presence of a sharp-edged vocal fold within the larynx.[2][87]\\nSpeed and acceleration\\nThe cheetah is the world's fastest land animal.[88][89][90][91][92] Estimates of the maximum speed attained range from 80 to 128 km/h (50 to 80 mph).[60][63] A commonly quoted value is 112 km/h (70 mph), recorded in 1957, but this measurement is disputed.[93] The mouth can not be opened as widely as in other cats given the shorter length of muscles between the jaw and the skull.[60][65] A study suggested that the limited retraction of the cheetah's claws may result from the earlier truncation of the development of the middle phalanx bone in cheetahs.[77]\\nThe cheetah has a total of 30 teeth; the dental formula is 3.1.3.13.1.2.1.\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"Cheetah - Wikipedia\",\n",
            "        \"source\": \"https://en.wikipedia.org/wiki/Cheetah\",\n",
            "        \"score\": 0.96423,\n",
            "        \"images\": null\n",
            "      }\n",
            "    },\n",
            "    {\n",
            "      \"pageContent\": \"One of two videos from National Geographic's award-winning multimedia coverage of cheetahs in the magazine's November 2012 iPad edition. See the other: http:...\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"The Science of a Cheetah's Speed | National Geographic\",\n",
            "        \"source\": \"https://www.youtube.com/watch?v=icFMTB0Pi0g\",\n",
            "        \"score\": 0.96071,\n",
            "        \"images\": null\n",
            "      }\n",
            "    },\n",
            "    {\n",
            "      \"pageContent\": \"Contact Us − +\\nAddress\\nSmithsonian's National Zoo & Conservation Biology Institute  3001 Connecticut Ave., NW  Washington, DC 20008\\nAbout the Zoo\\n−\\n+\\nCareers\\n−\\n+\\nNews & Media\\n−\\n+\\nFooter Donate\\n−\\n+\\nShop\\n−\\n+\\nFollow us on social media\\nSign Up for Emails\\nFooter - SI logo, privacy, terms Conservation Efforts\\nHistorically, cheetahs ranged widely throughout Africa and Asia, from the Cape of Good Hope to the Mediterranean, throughout the Arabian Peninsula and the Middle East, from Israel, India and Pakistan north to the northern shores of the Caspian and Aral Seas, and west through Uzbekistan, Turkmenistan, Afghanistan, and Pakistan into central India. Header Links\\nToday's hours: 8 a.m. to 4 p.m. (last entry 3 p.m.)\\nMega menu\\nAnimals Global Nav Links\\nElephant Cam\\nSee the Smithsonian's National Zoo's Asian elephants — Spike, Bozie, Kamala, Swarna and Maharani — both inside the Elephant Community Center and outside in their yards.\\n Conservation Global Nav Links\\nAbout the Smithsonian Conservation Biology Institute\\nCheetah\\nAcinonyx jubatus\\nBuilt for speed, the cheetah can accelerate from zero to 45 in just 2.5 seconds and reach top speeds of 60 to 70 mph, making it the fastest land mammal! Fun Facts\\nConservation Status\\nCheetah News\\nTaxonomic Information\\nAnimal News\\nNZCBI staff in Front Royal, Virginia, are mourning the loss of Walnut, a white-naped crane who became an internet sensation for choosing one of her keepers as her mate.\\n\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"Cheetah | Smithsonian's National Zoo and Conservation Biology Institute\",\n",
            "        \"source\": \"https://nationalzoo.si.edu/animals/cheetah\",\n",
            "        \"score\": 0.91577,\n",
            "        \"images\": null\n",
            "      }\n",
            "    },\n",
            "    {\n",
            "      \"pageContent\": \"The maximum speed cheetahs have been measured at is 114 km (71 miles) per hour, and they routinely reach velocities of 80–100 km (50–62 miles) per hour while pursuing prey.\\ncheetah,\\n(Acinonyx jubatus),\\none of the world’s most-recognizable cats, known especially for its speed. Their fur is dark and includes a thick yellowish gray mane along the back, a trait that presumably offers better camouflage and increased protection from high temperatures during the day and low temperatures at night during the first few months of life. Cheetahs eat a variety of small animals, including game birds, rabbits, small antelopes (including the springbok, impala, and gazelle), young warthogs, and larger antelopes (such as the kudu, hartebeest, oryx, and roan).\\n A cheetah eats a variety of small animals, including game birds, rabbits, small antelopes (including the springbok, impala, and gazelle), young warthogs, and larger antelopes (such as the kudu, hartebeest, oryx, and roan). Their faces are distinguished by prominent black lines that curve from the inner corner of each eye to the outer corners of the mouth, like a well-worn trail of inky tears.\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"Cheetah | Description, Speed, Habitat, Diet, Cubs, & Facts\",\n",
            "        \"source\": \"https://www.britannica.com/animal/cheetah-mammal\",\n",
            "        \"score\": 0.91163,\n",
            "        \"images\": null\n",
            "      }\n",
            "    },\n",
            "    {\n",
            "      \"pageContent\": \"If a lion comes along, the cheetah will abandon its catch -- it can't fight off a lion, and chances are, the cheetah will lose its life along with its prey if it doesn't get out of there fast enough.\\n Advertisement\\nLots More Information\\nMore Great Links\\nSources\\nPlease copy/paste the following text to properly cite this HowStuffWorks.com article:\\nAdvertisement\\nAdvertisement\\nAdvertisement\\nAdvertisement\\nAdvertisement If confronted, a roughly 125-pound cheetah will always run rather than fight -- it's too weak, light and thin to have any chance against something like a lion, which can be twice as long as a cheetah and weigh more than 400 pounds (181.4 kg) Cheetah moms spend a lot of time teaching their cubs to chase, sometimes dragging live animals back to the den so the cubs can practice the chase-and-catch process.\\n It's more like a bound at that speed, completing up to three strides per second, with only one foot on the ground at any time and several stages when feet don't touch the ground at all.\",\n",
            "      \"metadata\": {\n",
            "        \"title\": \"What makes a cheetah run so fast? | HowStuffWorks\",\n",
            "        \"source\": \"https://animals.howstuffworks.com/mammals/cheetah-speed.htm\",\n",
            "        \"score\": 0.89019,\n",
            "        \"images\": null\n",
            "      }\n",
            "    }\n",
            "  ]\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "const chain4 = retrieveMap\n",
        "  .assign({ context: formatDocs })\n",
        "  .assign({ answer: answerChain })\n",
        "  .pick([\"answer\", \"docs\"]);\n",
        "  \n",
        "// Note the documents have an article \"summary\" in the metadata that is now much longer than the\n",
        "// actual document page content. This summary isn't actually passed to the model.\n",
        "const res = await chain4.invoke(\"How fast are cheetahs?\");\n",
        "\n",
        "console.log(JSON.stringify(res, null, 2))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Check out the LangSmith trace [here](https://smith.langchain.com/public/b767cca0-6061-4208-99f2-7f522b94a587/r) to see the internals.\n",
        "\n",
        "## Next steps\n",
        "\n",
        "You've now learned a few ways to return citations from your QA chains.\n",
        "\n",
        "Next, check out some of the other guides in this section, such as [how to add chat history](/docs/how_to/qa_chat_history_how_to)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Deno",
      "language": "typescript",
      "name": "deno"
    },
    "language_info": {
      "file_extension": ".ts",
      "mimetype": "text/x.typescript",
      "name": "typescript",
      "nb_converter": "script",
      "pygments_lexer": "typescript",
      "version": "5.3.3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}
